<template>
  <div class="factory-management-view">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入工厂名称"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 250px;"
          clearable
          @keyup.enter.native="handleSearch"
        ></el-input>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
      </div>
      <div class="operation-area">
        <el-button type="primary" size="small" @click="handleAdd">新增工厂</el-button>
      </div>
    </div>

    <!-- 工厂列表表格 -->
    <el-table 
      :data="factoryList" 
      style="width: 100%; margin-top: 20px;" 
      border 
      v-loading="loading"
    >
      <el-table-column label="序号" width="60px" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="id" label="工厂ID" width="80px" align="center"></el-table-column> -->
      <el-table-column prop="factory_name" label="工厂名称" min-width="200px">
        <template slot-scope="scope">
          <span>{{ scope.row.factory_name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="工厂地址" min-width="300px">
        <template slot-scope="scope">
          <span>{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="管理员信息" min-width="300px">
        <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleLookAdminInfo(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="180px" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑工厂弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      center
    >
      <el-form :model="form" :rules="formRules" ref="form" label-width="100px">
        <el-form-item label="工厂名称" prop="factory_name">
          <el-input 
            v-model="form.factory_name" 
            placeholder="请输入工厂名称"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="工厂地址" prop="address">
          <el-input 
            v-model="form.address" 
            type="textarea"
            :rows="3"
            placeholder="请输入工厂地址"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    
    <!-- 管理员信息弹窗 -->
    <el-dialog
      :title="`${currentFactoryName} - 管理员信息`"
      :visible.sync="adminDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      center
    >
      <!-- 弹窗头部操作区域 -->
      <div class="dialog-header-actions" style="margin-bottom: 20px;">
        <el-button type="primary" size="small" @click="handleAddAdmin">
          <i class="el-icon-plus"></i> 新增管理员
        </el-button>
      </div>
      
      <div v-loading="adminLoading">
        <el-table
          :data="factoryAdminList"
          border
          stripe
          style="width: 100%"
        > 
          <el-table-column prop="Name" label="姓名" min-width="120px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.Name || '未知' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="Iphone" label="手机号" min-width="150px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.Iphone || '未知' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sex" label="性别" width="100px"  align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.Sex === 1 ? 'primary' : 'success'">
                {{ scope.row.Sex === 1 ? '男' : '女' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" min-width="150px" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDeleteAdmin(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 空数据提示 -->
        <div v-if="factoryAdminList.length === 0 && !adminLoading" class="empty-data">
          <el-empty description="暂无管理员信息" :image-size="80"></el-empty>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAdminDialog">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增管理员弹窗 -->
    <el-dialog
      :title="`${currentFactoryName} - 新增管理员`"
      :visible.sync="addAdminDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      center
    >
      <el-form :model="adminForm" :rules="adminFormRules" ref="adminForm" label-width="100px">
        <el-form-item label="姓名" prop="Name">
          <el-input 
            v-model="adminForm.Name" 
            placeholder="请输入管理员姓名"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="Iphone">
          <el-input 
            v-model="adminForm.Iphone" 
            placeholder="请输入手机号"
            maxlength="11"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="adminForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddAdminDialog">取消</el-button>
        <el-button type="primary" @click="submitAdminForm" :loading="submitAdminLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { factoryAdminList,factoryAdminAdd,factoryAdminDel,getFactoryList, addFactory, editFactory, deleteFactory } from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';

export default {
  name: 'FactoryManagementView',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      
      // 表格数据
      factoryList: [],
      loading: false,

      //工厂管理员数据
      factoryAdminList:[],
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '新增工厂',
      isEdit: false,
      submitLoading: false,
      
      // 表单数据
      form: {
        id: '',
        factory_name: '',
        address: ''
      },
      
      // 表单验证规则
      formRules: {
        factory_name: [
          { required: true, message: '请输入工厂名称', trigger: 'blur' },
          { min: 2, max: 100, message: '工厂名称长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入工厂地址', trigger: 'blur' },
          { min: 5, max: 500, message: '工厂地址长度在 5 到 500 个字符', trigger: 'blur' }
        ]
      },

      // 管理员信息弹窗相关
      adminDialogVisible: false,
      adminLoading: false,
      currentFactoryName: '',
      currentFactoryId: '',

      // 新增管理员弹窗相关
      addAdminDialogVisible: false,
      adminForm: {
        factoryId: '',
        Name: '',
        Iphone: '',
        sex: 1 // 默认男
      },
      adminFormRules: {
        Name: [
          { required: true, message: '请输入管理员姓名', trigger: 'blur' },
          { min: 2, max: 50, message: '管理员姓名长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        Iphone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      },
      submitAdminLoading: false,
    };
  },
  methods: {
    
    // 获取工厂列表
    async fetchFactoryList() {
      this.loading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const params = {
          keyword: this.searchKeyword,
          page: this.currentPage,
          pageSize: this.pageSize
        };
        
        const response = await getFactoryList(params);
        
        if (response.data && response.data.code === 1) {
          // API成功返回数据
          this.factoryList = response.data.data.data || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$message.error(response.data.msg || '获取工厂列表失败');
        }
      } catch (error) {
        console.error('获取工厂列表失败:', error);
        if (checkTokenFromError(error)) {
          // Token无效或过期
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          // 其他错误
          this.$message.error('获取工厂列表失败');
        }
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchFactoryList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.currentPage = 1;
      this.fetchFactoryList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchFactoryList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchFactoryList();
    },

    // 新增工厂
    handleAdd() {
      this.dialogTitle = '新增工厂';
      this.isEdit = false;
      this.form = {
        id: '',
        factory_name: '',
        address: ''
      };
      this.dialogVisible = true;
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },

    // 编辑工厂
    handleEdit(row) {
      this.dialogTitle = '编辑工厂';
      this.isEdit = true;
      this.form = {
        id: row.id,
        factory_name: row.factory_name,
        address: row.address
      };
      this.dialogVisible = true;
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },

    //查看工厂管理员列表
    async handleLookAdminInfo(row){
      this.adminDialogVisible = true;
      this.adminLoading = true;
      this.factoryAdminList = [];
      this.currentFactoryName = row.factory_name || '未知工厂';
      this.currentFactoryId = row.id;
      
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const response = await factoryAdminList(row.id);
        
        if (response.data && response.data.code) {
          this.factoryAdminList = response.data.msg || [];
          if (this.factoryAdminList.length === 0) {
            this.$message.info('该工厂暂无管理员信息');
          }
        } else {
          this.$message.error(response.data.msg || '获取管理员信息失败');
        }
      } catch (error) {
        console.error('获取管理员信息失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('获取管理员信息失败');
        }
      } finally {
        this.adminLoading = false;
      }
    },

    // 关闭管理员信息弹窗
    closeAdminDialog() {
      this.adminDialogVisible = false;
      this.factoryAdminList = [];
      this.currentFactoryName = '';
      this.currentFactoryId = '';
      this.adminLoading = false;
    },

    // 关闭新增管理员弹窗
    closeAddAdminDialog() {
      this.addAdminDialogVisible = false;
      this.adminForm = {
        factoryId: '',
        Name: '',
        Iphone: '',
        sex: 1
      };
      this.$nextTick(() => {
        this.$refs.adminForm && this.$refs.adminForm.clearValidate();
      });
    },

    // 新增管理员
    handleAddAdmin() {
      if (!this.currentFactoryId) {
        this.$message.error('请先选择工厂');
        return;
      }
      
      this.addAdminDialogVisible = true;
      this.adminForm = {
        factoryId: this.currentFactoryId,
        Name: '',
        Iphone: '',
        sex: 1 // 默认男
      };
      this.$nextTick(() => {
        this.$refs.adminForm && this.$refs.adminForm.clearValidate();
      });
    },

    // 刷新管理员列表
    async refreshAdminList() {
      if (!this.currentFactoryId) return;
      
      this.adminLoading = true;
      try {
        const response = await factoryAdminList(this.currentFactoryId);
        
        if (response.data && response.data.code) {
          this.factoryAdminList = response.data.msg || [];
        } else {
          this.$message.error(response.data.msg || '获取管理员信息失败');
        }
      } catch (error) {
        console.error('刷新管理员列表失败:', error);
        this.$message.error('刷新管理员列表失败');
      } finally {
        this.adminLoading = false;
      }
    },

    // 删除工厂
    async handleDelete(row) {
      try {
        await this.$confirm(`确定要删除工厂"${row.factory_name}"吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const response = await deleteFactory(row.id);
        
        if (response.data && response.data.code === 1) {
          this.$message.success('删除工厂成功');
          this.fetchFactoryList();
        } else {
          this.$message.error(response.data.msg || '删除工厂失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除工厂失败:', error);
          if (checkTokenFromError(error)) {
            this.$message.error('登录已过期，请重新登录');
            handleTokenExpired();
          } else {
            this.$message.error('删除工厂失败');
          }
        }
      }
    },

    // 提交表单
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true;
          try {
            // 检查token是否存在
            if (!checkToken()) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
              return;
            }

            const api = this.isEdit ? editFactory : addFactory;
            const response = await api(this.form);

            if (response.data && response.data.code === 1) {
              this.$message.success(this.isEdit ? '编辑工厂成功' : '新增工厂成功');
              this.dialogVisible = false;
              this.fetchFactoryList();
            } else {
              this.$message.error(response.data.msg || '操作失败');
            }
          } catch (error) {
            console.error('提交工厂信息失败:', error);
            if (checkTokenFromError(error)) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              this.$message.error('操作失败');
            }
          } finally {
            this.submitLoading = false;
          }
        }
      });
    },

    // 提交新增管理员表单
    async submitAdminForm() {
      this.$refs.adminForm.validate(async (valid) => {
        if (valid) {
          this.submitAdminLoading = true;
          try {
            // 检查token是否存在
            if (!checkToken()) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
              return;
            }

            const response = await factoryAdminAdd(this.adminForm);

                         if (response.data && response.data.code) {
               this.$message.success('新增管理员成功');
               this.addAdminDialogVisible = false;
               // 重新获取当前工厂的管理员列表
               this.refreshAdminList();
               // 重置表单
               this.adminForm = {
                 factoryId: this.currentFactoryId,
                 Name: '',
                 Iphone: '',
                 sex: 1
               };
             } else {
              this.$message.error(response.data.msg || '新增管理员失败');
            }
          } catch (error) {
            console.error('新增管理员失败:', error);
            if (checkTokenFromError(error)) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              this.$message.error('新增管理员失败');
            }
          } finally {
            this.submitAdminLoading = false;
          }
        }
      });
    },

    // 删除管理员
    async handleDeleteAdmin(row) {
      try {
        // 调试信息：打印行数据
        console.log('删除管理员行数据:', row);
        
        if (!row || !row.Name) {
          this.$message.error('管理员信息不完整');
          return;
        }
        
        await this.$confirm(`确定要删除管理员"${row.Name}"吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        // 确定使用哪个字段作为管理员ID
        const adminId = row.UserId || row.id || row.userId;
        if (!adminId) {
          this.$message.error('无法获取管理员ID');
          console.error('管理员数据缺少ID字段:', row);
          return;
        }

        const response = await factoryAdminDel(adminId);

        if (response.data && response.data.code) {
          this.$message.success('删除管理员成功');
          // 重新获取当前工厂的管理员列表
          this.refreshAdminList();
        } else {
          this.$message.error(response.data.msg || '删除管理员失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除管理员失败:', error);
          if (checkTokenFromError(error)) {
            this.$message.error('登录已过期，请重新登录');
            handleTokenExpired();
          } else {
            this.$message.error('删除管理员失败');
          }
        }
      }
    }
  },
  
  created() {
    this.fetchFactoryList();
  }
};
</script>

<style scoped>
.factory-management-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.operation-area {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式 */
.el-table {
  border: 1px solid #EBEEF5;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

.el-table td, .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

.el-table th:last-child,
.el-table td:last-child {
  border-right: none;
}

/* 空数据提示样式 */
.empty-data {
  text-align: center;
  padding: 40px 0;
}

/* 管理员信息弹窗样式 */
.el-dialog__body {
  padding: 20px;
}

.el-table {
  margin-bottom: 0;
}

/* 弹窗头部操作区域样式 */
.dialog-header-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 15px;
}
</style> 